/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
/**
 * @author zouLing
 * @date 2018/5/25
 * @Description:
*/
import { ListView, NavBar, Icon, InputItem, Button, Card, Flex, List, SwipeAction, WingBlank, Modal } from 'antd-mobile';
import React from 'react';
import { createForm } from 'rc-form';
import { routerRedux } from 'dva/router';
import {
  connect,
} from 'dva';
import styles from './shoppingCar.css';
import img from '../assets/img/shopping.jpg';
import common from './common.css';

const prompt = Modal.prompt;
const Item = List.Item;
const alert = Modal.alert;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let moneyKeyboardWrapProps;
if (isIPhone) {
  moneyKeyboardWrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

class ShoppingCar extends React.Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row2,
    });
    this.state = {
      flag: 1,
      number: 0,
      modal1: false,
      singelData: [],
      dataSource,
      isLoading: true,
      height: document.documentElement.clientHeight * 4 / 5,
    };
  }
  componentWillReceiveProps(nexprops) {
    let carlist2 = [];
    carlist2 = nexprops.car.carList.map(v => v);
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(carlist2),
    });
  }

  // 滚动请求下一页数据
  onEndReached = (event) => {
    this.setState({ isLoading: true });
    const { isLastPage, nextPage, customerId } = this.props.car;
    if (!isLastPage) {
      this.props.dispatch({
        type: 'car/getCarData',
        payload: { pageNum: nextPage, pageSize: 10, customerId },
      });
    } else {
      this.setState({ isLoading: false });
    }
  }
   // 关闭输入弹框
   onClose = () => {
     let array = {};
     setTimeout(() => {
       if (this.state.number) {
         array = this.state.singelData;
         array.count = this.state.number;
         this.setState({
           singelData: array,
           modal1: false,
         });
         this.changeNumber(this.state.singelData);
       } else {
         alert('警告', '数量不能为0,请重新填写数量', [
           { text: '确定' },
         ]);
       }
     }, 100);
   }
   //  失去焦点后得到输入的值
   onBlue = (value) => {
     this.setState({
       number: parseFloat(value),
     });
   }
   showModal = row => (e) => {
     this.setState({
       number: row.count,
     });
     this.props.form.resetFields(); // 清空上次的输入
     this.props.form.setFieldsValue({// 设置初始值
       number: `${row.count}`,
     });
     e.preventDefault(); // 修复 Android 上点击穿透
     this.setState({
       modal1: true,
       singelData: row,
     });
   }
  // 删除某一行的数据
  delectData=(row) => {
    const obj = {};
    obj.internalTradeId = row.internalTradeId;
    this.props.dispatch({
      type: 'car/delectCarData',
      payload: obj,
    });
    this.state.flag = 0;
  }
  // 清空购物车
  deleteAll = () => {
    alert('清除购物车', '是否清除', [
      { text: '否' },
      { text: '是',
        onPress: () => this.props.dispatch({
          type: 'car/delectCarAllData',
        }) },
    ]);
  }
  // 确认订单
   sureOrder= () => {
     alert('确认订单', '是否确认', [
       { text: '否' },
       { text: '是',
         onPress: () => this.props.dispatch(
           routerRedux.push('/orderDetials')) },
     ]);
   }
   // 修改某一行的数据
  changeNumber = (obj) => {
    const param = {};
    param.count = obj.count;
    param.internalTradeId = obj.internalTradeId;
    this.props.dispatch({
      type: 'car/editCarData',
      payload: param,
    });
  }
  render() {
    const { singelData } = this.state;
    const { getFieldProps } = this.props.form;
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    const row = (rowData, sectionID, rowID) => {
      return (
        <div
          key={rowID}
        >
          <SwipeAction
            autoClose
            useBodyScroll
            right={[
              {
                text: '删除',
                onPress: () => {
                  this.delectData(rowData);
                },
                style: { backgroundColor: '#F4333C', color: 'white', padding: 20 },
              },
            ]}
          >
            <Card full="true">
              <Card.Header
                
                title={<span style={{ color: 'rgb(255, 110, 39)', fontWeight: 'bold' }}>{rowData.internalName}({rowData.unitName})</span>}
                extra={<span>数量:{rowData.count ? rowData.count : 1}</span>}
              />
              <Card.Body>
                <div><span style={{ fontWeight: 'bold' }}>类型:</span>{rowData.internalType}</div>
              </Card.Body>
              <Card.Footer
                extra={
                  <div><Button style={{ margin: '2px' }} type="warning" size="small" inline onClick={() => this.delectData(rowData)}>删除</Button>
                    <Button
                      type="primary"
                      size="small"
                      inline
                      style={{ margin: '2px' }}
                      onClick={this.showModal(rowData)}
                    >修改数量
                    </Button>
                  </div>}
              />
            </Card>
          </SwipeAction>
        </div>);
    };
    return (
      <div style={{ fontFamily: 'Microsoft ' }}>
        <NavBar
          mode="light"
          style={{ backgroundColor: '#F0F0F0' }}
          icon={<Icon type="left" />}
          rightContent={<span style={{ padding: '0 5px', fontSize: '12px', color: 'black' }} onClick={this.deleteAll}>清空购物车</span>
        }
          onLeftClick={() => this.props.dispatch(
            routerRedux.push('/shoppingCar'))}
        >购物车
        </NavBar>
        <div>
          {(this.props.car.carList.length !== 0) ? (
            <div >
              <ListView
                ref={el => this.lv = el}
                dataSource={this.state.dataSource}
                renderFooter={() => (
                  <div style={{ padding: 30, textAlign: 'center' }}>
                    {this.state.isLoading ? '吃奶的力气加载中' : '我是有底线的'}
                  </div>
                )}
                renderRow={row}
                renderSeparator={separator}
                style={{
                height: this.state.height,
                overflow: 'auto',
                }}
                pageSize={3}
                onEndReachedThreshold={10}
                onEndReached={this.onEndReached}
              />
              <Modal
                visible={this.state.modal1}
                transparent
                title={`${singelData.internalName}的数量`}
                footer={[{ text: '确定', onPress: () => { this.onClose(); } }]}
              >
                <List>
                  <InputItem
                    {...getFieldProps('number', {
                   normalize: (v, prev) => {
                     if (v && !/^(([1-9]\d*)|0)(\.\d{0,2}?)?$/.test(v)) {
                       if (v === '.') {
                         return '0.';
                       }
                       return prev;
                     }
                     return v;
                   },
                 })}
                    type="money"
                    border="true"
                    moneyKeyboardAlign="left"
                    onBlur={v => this.onBlue(v)}
                    updatePlaceholder="true"
                    moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                    clear="true"
                  />
                </List>
              </Modal>
              <div className={common.bottomStyle}>
                <Flex justify="between">
                  <Flex.Item className={common.bottomTotal}><span style={{ fontSize: '15px' }}>共{this.props.global.carListNum}</span>种</Flex.Item>
                  <Flex.Item style={{ margin: 0 }} onClick={this.sureOrder}className={common.bottomButtom}><span style={{ fontSize: '15px' }}>提交订单</span></Flex.Item>
                </Flex>
              </div>
            </div>
        ) :
        (
          <div className={styles.shoppingNone}>
            <img style={{ width: '50%' }} src={img} />
            <div>购物车空空如也,去逛逛吧</div>
            <Button className={styles.shoppingNoneButtom} onClick={() => this.props.dispatch(routerRedux.push('/'))}>去逛逛</Button>
          </div>)}
        </div>
      </div>
    );
  }
}
export default connect(({ car, global }) => ({ car, global }))(createForm()(ShoppingCar));
